<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/assets/img/favicon.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/assets/img/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/assets/img/favicon.ico">
  <link rel="mask-icon" href="/assets/img/favicon.ico" color="#222">
  <meta http-equiv="Cache-Control" content="no-transform">
  <meta http-equiv="Cache-Control" content="no-siteapp">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-bounce.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"lzqblog.top","root":"/","scheme":"Mist","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"always","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"default"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="This post will give a simple introduction to Linux kernel module(Part I.). Linux kernel module简介(一)">
<meta property="og:type" content="article">
<meta property="og:title" content="Linux kernel module(1)">
<meta property="og:url" content="https://lzqblog.top/2018-12-09/Linux-kernel-module-1/index.html">
<meta property="og:site_name" content="Coding Spirit">
<meta property="og:description" content="This post will give a simple introduction to Linux kernel module(Part I.). Linux kernel module简介(一)">
<meta property="article:published_time" content="2018-12-09T03:01:48.000Z">
<meta property="article:modified_time" content="2018-12-16T12:08:54.000Z">
<meta property="article:author" content="Coding Spirit">
<meta property="article:tag" content="Linux">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://lzqblog.top/2018-12-09/Linux-kernel-module-1/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-Hans'
  };
</script>

  <title>Linux kernel module(1) | Coding Spirit</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-154617667-1"></script>
    <script>
      if (CONFIG.hostname === location.hostname) {
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'UA-154617667-1');
      }
    </script>






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Coding Spirit</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">一位程序员，比较帅的那种</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>Categories</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>Search
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="Searching..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/codingspirit" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://lzqblog.top/2018-12-09/Linux-kernel-module-1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/assets/img/coding_spirit.jpg">
      <meta itemprop="name" content="Coding Spirit">
      <meta itemprop="description" content="毕业于OUC，现就职于Amazon">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Coding Spirit">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Linux kernel module(1)
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2018-12-09 11:01:48" itemprop="dateCreated datePublished" datetime="2018-12-09T11:01:48+08:00">2018-12-09</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">Edited on</span>
                <time title="Modified: 2018-12-16 20:08:54" itemprop="dateModified" datetime="2018-12-16T20:08:54+08:00">2018-12-16</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">In</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E7%BC%96%E7%A8%8B%E7%9B%B8%E5%85%B3/" itemprop="url" rel="index"><span itemprop="name">编程相关</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="Views" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">Views: </span>
              <span id="busuanzi_value_page_pv"></span>
            </span><br>
            <span class="post-meta-item" title="Symbols count in article">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">Symbols count in article: </span>
              <span>6.9k</span>
            </span>
            <span class="post-meta-item" title="Reading time">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">Reading time &asymp;</span>
              <span>6 mins.</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>This post will give a simple introduction to Linux kernel module(Part I.).</p>
<p>Linux kernel module简介(一)</p>
<a id="more"></a>
<p>When your system has a new external chip connected(I2C,SPI,GPIO etc.), you might need to write a driver for it by yourself. Normally this driver will be implemented as a kernel module. </p>
<p>Kernel module development is a complex task and it’s hard to make it clear in one simple post. If you want to learn more, a good choice is taking a look at Linux kernel source code.</p>
<h2 id="The-simplest-example-of-kernel-module"><a href="#The-simplest-example-of-kernel-module" class="headerlink" title="The simplest example of kernel module"></a>The simplest example of kernel module</h2><h3 id="Source-code"><a href="#Source-code" class="headerlink" title="Source code"></a>Source code</h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// file:simple_module.c</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;linux/init.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;linux/module.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;linux/printk.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">int</span> __<span class="function">init <span class="title">sample_module_init</span><span class="params">(<span class="keyword">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	printk(KERN_INFO <span class="string">"Hello world!\n"</span>);</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">void</span> __<span class="function"><span class="built_in">exit</span> <span class="title">sample_module_exit</span><span class="params">(<span class="keyword">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	printk(KERN_INFO <span class="string">"Bye!\n"</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">module_init(sample_module_init);</span><br><span class="line"></span><br><span class="line">module_exit(sample_module_exit);</span><br><span class="line"></span><br><span class="line">MODULE_AUTHOR(<span class="string">"Coding Spirit &lt;coding@spirit.com&gt;"</span>);</span><br><span class="line">MODULE_LICENSE(<span class="string">"GPL v2"</span>);</span><br></pre></td></tr></table></figure>

<p>This simple example shows basic structure of kernel module. A <strong>init</strong> function and a <strong>exit</strong> function must be declared, to avoid warnings, <strong>MODULE_AUTHOR</strong> and <strong>MODULE_LICENSE</strong> is needed as well.</p>
<h3 id="Makefile"><a href="#Makefile" class="headerlink" title="Makefile"></a>Makefile</h3><p>To compile it to kernel module(.ko) file, we need to write a Makefile for it.</p>
<figure class="highlight mk"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">simple-module-objs := simple_module.o</span><br><span class="line"></span><br><span class="line">obj-m := simple-module.o</span><br></pre></td></tr></table></figure>
<p>In this Makefile <strong>$(<executable>-objs)</executable></strong> lists all objects used to link the final executable, <strong>obj-m</strong> means loadable module goals, it will generate a standalone .ko file, then we can use <strong>insmod</strong> to install it. If change it to <strong>obj-y</strong>, it will be compiled into kernel.</p>
<h3 id="Test-this-module"><a href="#Test-this-module" class="headerlink" title="Test this module"></a>Test this module</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># clear debug message first</span></span><br><span class="line">dmesg -c</span><br><span class="line"><span class="comment"># see modules already installed</span></span><br><span class="line">lsmod</span><br><span class="line"><span class="comment"># install simple module</span></span><br><span class="line">insmod simple-module.ko</span><br><span class="line"><span class="comment"># check debug message</span></span><br><span class="line">dmesg</span><br><span class="line"><span class="comment"># remove simple module</span></span><br><span class="line">rmmod simple-module.ko</span><br><span class="line">dmesg</span><br></pre></td></tr></table></figure>

<h3 id="What-are-module-init-exit-and-init-exit"><a href="#What-are-module-init-exit-and-init-exit" class="headerlink" title="What are module_init/exit and __init/exit"></a>What are module_init/exit and __init/exit</h3><p>module_init and module_exit are macros to help register module init and exit functions. Use your F12, go to definition:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">define</span> __define_initcall(fn, id) \</span></span><br><span class="line">	<span class="keyword">static</span> <span class="keyword">initcall_t</span> __initcall_#<span class="meta">#fn##id __used \</span></span><br><span class="line">	__attribute__((__section__(<span class="string">".initcall"</span> #id <span class="string">".init"</span>))) = fn;</span><br></pre></td></tr></table></figure>

<p><em>fn</em> is your function name, <em>id</em> stand for priority, for module_init, this level will be set as 6.</p>
<p>After using this marco, your init function will be called when <strong>do_initcalls</strong> was called(<em>init/main.c</em>)</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">void</span> __<span class="function">init <span class="title">do_initcalls</span><span class="params">(<span class="keyword">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">int</span> level;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">for</span> (level = <span class="number">0</span>; level &lt; ARRAY_SIZE(initcall_levels) - <span class="number">1</span>; level++)</span><br><span class="line">		do_initcall_level(level);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>as for marco <strong>__init</strong> , It tells the compiler to put this function in a special section, which is declared in vmlinux.lds. <strong>__init</strong> puts the function in the “.init.text” section.</p>
<p>Take a look at where it defined(/linux-4.9/include/linux/init.h):</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* These macros are used to mark some functions or</span></span><br><span class="line"><span class="comment"> * initialized data (doesn't apply to uninitialized data)</span></span><br><span class="line"><span class="comment"> * as `initialization' functions. The kernel can take this</span></span><br><span class="line"><span class="comment"> * as hint that the function is used only during the initialization</span></span><br><span class="line"><span class="comment"> * phase and free up used memory resources after*/</span></span><br><span class="line"> </span><br><span class="line"><span class="comment">/* These are for everybody (although not all archs will actually</span></span><br><span class="line"><span class="comment">   discard it in modules) */</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> __init		__section(.init.text)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> __initdata	__section(.init.data)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> __exitdata	__section(.exit.data)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> __exit_call	__used __section(.exitcall.exit)</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">ifdef</span> MODULE</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> __exit		__section(.exit.text)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">else</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> __exit		__used __section(.exit.text)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></span><br></pre></td></tr></table></figure>
<p>As we can see in comment, if you use <strong>__init</strong> to mark it, memory will be released after initialization.</p>
<h2 id="A-I2C-module"><a href="#A-I2C-module" class="headerlink" title="A I2C module"></a>A I2C module</h2><p>This simple module is useless, let’s take a look at a more useful one: <a href="https://github.com/torvalds/linux/blob/6f0d349d922ba44e4348a17a78ea51b7135965b1/drivers/iio/light/st_uvis25_i2c.c" target="_blank" rel="noopener"><em>linux/drivers/iio/light/st_uvis25_i2c.c</em></a></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * STMicroelectronics uvis25 i2c driver</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * Copyright 2017 STMicroelectronics Inc.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * Lorenzo Bianconi &lt;lorenzo.bianconi83@gmail.com&gt;</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * Licensed under the GPL-2.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;linux/kernel.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;linux/module.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;linux/acpi.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;linux/i2c.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;linux/slab.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;linux/regmap.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">"st_uvis25.h"</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> UVIS25_I2C_AUTO_INCREMENT	BIT(7)</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">const</span> <span class="class"><span class="keyword">struct</span> <span class="title">regmap_config</span> <span class="title">st_uvis25_i2c_regmap_config</span> = &#123;</span></span><br><span class="line">	.reg_bits = <span class="number">8</span>,</span><br><span class="line">	.val_bits = <span class="number">8</span>,</span><br><span class="line">	.write_flag_mask = UVIS25_I2C_AUTO_INCREMENT,</span><br><span class="line">	.read_flag_mask = UVIS25_I2C_AUTO_INCREMENT,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">int</span> <span class="title">st_uvis25_i2c_probe</span><span class="params">(struct i2c_client *client,</span></span></span><br><span class="line"><span class="function"><span class="params">			       <span class="keyword">const</span> struct i2c_device_id *id)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="class"><span class="keyword">struct</span> <span class="title">regmap</span> *<span class="title">regmap</span>;</span></span><br><span class="line"></span><br><span class="line">	regmap = devm_regmap_init_i2c(client, &amp;st_uvis25_i2c_regmap_config);</span><br><span class="line">	<span class="keyword">if</span> (IS_ERR(regmap)) &#123;</span><br><span class="line">		dev_err(&amp;client-&gt;dev, <span class="string">"Failed to register i2c regmap %d\n"</span>,</span><br><span class="line">			(<span class="keyword">int</span>)PTR_ERR(regmap));</span><br><span class="line">		<span class="keyword">return</span> PTR_ERR(regmap);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> st_uvis25_probe(&amp;client-&gt;dev, client-&gt;irq, regmap);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">const</span> <span class="class"><span class="keyword">struct</span> <span class="title">of_device_id</span> <span class="title">st_uvis25_i2c_of_match</span>[] = &#123;</span></span><br><span class="line">	&#123; .compatible = <span class="string">"st,uvis25"</span>, &#125;,</span><br><span class="line">	&#123;&#125;,</span><br><span class="line">&#125;;</span><br><span class="line">MODULE_DEVICE_TABLE(of, st_uvis25_i2c_of_match);</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">const</span> <span class="class"><span class="keyword">struct</span> <span class="title">i2c_device_id</span> <span class="title">st_uvis25_i2c_id_table</span>[] = &#123;</span></span><br><span class="line">	&#123; ST_UVIS25_DEV_NAME &#125;,</span><br><span class="line">	&#123;&#125;,</span><br><span class="line">&#125;;</span><br><span class="line">MODULE_DEVICE_TABLE(i2c, st_uvis25_i2c_id_table);</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">struct</span> <span class="title">i2c_driver</span> <span class="title">st_uvis25_driver</span> = &#123;</span></span><br><span class="line">	.driver = &#123;</span><br><span class="line">		.name = <span class="string">"st_uvis25_i2c"</span>,</span><br><span class="line">		.pm = &amp;st_uvis25_pm_ops,</span><br><span class="line">		.of_match_table = of_match_ptr(st_uvis25_i2c_of_match),</span><br><span class="line">	&#125;,</span><br><span class="line">	.probe = st_uvis25_i2c_probe,</span><br><span class="line">	.id_table = st_uvis25_i2c_id_table,</span><br><span class="line">&#125;;</span><br><span class="line">module_i2c_driver(st_uvis25_driver);</span><br><span class="line"></span><br><span class="line">MODULE_AUTHOR(<span class="string">"Lorenzo Bianconi &lt;lorenzo.bianconi83@gmail.com&gt;"</span>);</span><br><span class="line">MODULE_DESCRIPTION(<span class="string">"STMicroelectronics uvis25 i2c driver"</span>);</span><br><span class="line">MODULE_LICENSE(<span class="string">"GPL v2"</span>);</span><br></pre></td></tr></table></figure>

<h3 id="What-are-module-i2c-driver-and-MODULE-DEVICE-TABLE"><a href="#What-are-module-i2c-driver-and-MODULE-DEVICE-TABLE" class="headerlink" title="What are module_i2c_driver and MODULE_DEVICE_TABLE"></a>What are module_i2c_driver and MODULE_DEVICE_TABLE</h3><p>Like module_init we mentioned, they are marcos as well. Use your holy F12:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * module_i2c_driver() - Helper macro for registering a modular I2C driver</span></span><br><span class="line"><span class="comment"> * @__i2c_driver: i2c_driver struct</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * Helper macro for I2C drivers which do not do anything special in module</span></span><br><span class="line"><span class="comment"> * init/exit. This eliminates a lot of boilerplate. Each module may only</span></span><br><span class="line"><span class="comment"> * use this macro once, and calling it replaces module_init() and module_exit()</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> module_i2c_driver(__i2c_driver) \</span></span><br><span class="line">	module_driver(__i2c_driver, i2c_add_driver, \</span><br><span class="line">			i2c_del_driver)</span><br></pre></td></tr></table></figure>
<p>As for <strong>module_driver</strong>, marco AGAIN:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * module_driver() - Helper macro for drivers that don't do anything</span></span><br><span class="line"><span class="comment"> * special in module init/exit. This eliminates a lot of boilerplate.</span></span><br><span class="line"><span class="comment"> * Each module may only use this macro once, and calling it replaces</span></span><br><span class="line"><span class="comment"> * module_init() and module_exit().</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * @__driver: driver name</span></span><br><span class="line"><span class="comment"> * @__register: register function for this driver type</span></span><br><span class="line"><span class="comment"> * @__unregister: unregister function for this driver type</span></span><br><span class="line"><span class="comment"> * @...: Additional arguments to be passed to __register and __unregister.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * Use this macro to construct bus specific macros for registering</span></span><br><span class="line"><span class="comment"> * drivers, and do not use it on its own.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> module_driver(__driver, __register, __unregister, ...) \</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">int</span> __init __driver##_init(<span class="keyword">void</span>) \</span><br><span class="line">&#123; \</span><br><span class="line">	<span class="keyword">return</span> __register(&amp;(__driver) , ##__VA_ARGS__); \</span><br><span class="line">&#125; \</span><br><span class="line">module_init(__driver##_init); \</span><br><span class="line"><span class="keyword">static</span> <span class="keyword">void</span> __exit __driver##_exit(<span class="keyword">void</span>) \</span><br><span class="line">&#123; \</span><br><span class="line">	__unregister(&amp;(__driver) , ##__VA_ARGS__); \</span><br><span class="line">&#125; \</span><br><span class="line">module_exit(__driver##_exit);</span><br></pre></td></tr></table></figure>

<p>As you can see, those marcos actually are encapsulations of module_init/exit.</p>
<p>And for <strong>MODULE_DEVICE_TABLE</strong>, it’s just help to create an alias, if there is any nodes in <strong>dts</strong> has the same <strong>compatible</strong> with your drivers, <strong>probe</strong> function will be called.<br>As a driver writer, you have no idea how will user enumerate it(By of or i2c), so provide both of them is necessary.</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">ifdef</span> MODULE</span></span><br><span class="line"><span class="comment">/* Creates an alias so file2alias.c can find device table. */</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> MODULE_DEVICE_TABLE(type, name)					\</span></span><br><span class="line">extern typeof(name) __mod_##type##__##name##_device_table		\</span><br><span class="line">  __attribute__ ((unused, alias(__stringify(name))))</span><br><span class="line"><span class="meta">#<span class="meta-keyword">else</span>  <span class="comment">/* !MODULE */</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> MODULE_DEVICE_TABLE(type, name)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></span><br></pre></td></tr></table></figure>
<p><strong>regmap</strong> etc. will be discussed in Part II. </p>
<p>To be continued…</p>

    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>Post author:  </strong>Coding Spirit
  </li>
  <li class="post-copyright-link">
    <strong>Post link: </strong>
    <a href="https://lzqblog.top/2018-12-09/Linux-kernel-module-1/" title="Linux kernel module(1)">https://lzqblog.top/2018-12-09/Linux-kernel-module-1/</a>
  </li>
  <li class="post-copyright-license">
    <strong>Copyright Notice:  </strong>All articles in this blog are licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> unless stating additionally.
  </li>
</ul>
</div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/Linux/" rel="tag"><i class="fa fa-tag"></i> Linux</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2018-11-24/Markdown-frequently-used-syntax/" rel="prev" title="Markdown frequently used syntax">
      <i class="fa fa-chevron-left"></i> Markdown frequently used syntax
    </a></div>
      <div class="post-nav-item">
    <a href="/2018-12-16/Linux-kernel-module-2/" rel="next" title="Linux kernel module(2)">
      Linux kernel module(2) <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="gitalk-container"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#The-simplest-example-of-kernel-module"><span class="nav-number">1.</span> <span class="nav-text">The simplest example of kernel module</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Source-code"><span class="nav-number">1.1.</span> <span class="nav-text">Source code</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Makefile"><span class="nav-number">1.2.</span> <span class="nav-text">Makefile</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Test-this-module"><span class="nav-number">1.3.</span> <span class="nav-text">Test this module</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#What-are-module-init-exit-and-init-exit"><span class="nav-number">1.4.</span> <span class="nav-text">What are module_init&#x2F;exit and __init&#x2F;exit</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#A-I2C-module"><span class="nav-number">2.</span> <span class="nav-text">A I2C module</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#What-are-module-i2c-driver-and-MODULE-DEVICE-TABLE"><span class="nav-number">2.1.</span> <span class="nav-text">What are module_i2c_driver and MODULE_DEVICE_TABLE</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Coding Spirit"
      src="/assets/img/coding_spirit.jpg">
  <p class="site-author-name" itemprop="name">Coding Spirit</p>
  <div class="site-description" itemprop="description">毕业于OUC，现就职于Amazon</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">113</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">39</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/codingspirit" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;codingspirit" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:596544399@qq.com" title="E-Mail → mailto:596544399@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

      
        
          <div id="musicPlayerPost">
            <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=400876433&auto=0&height=66"></iframe>
          </div>
        
      
      

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Powered by Coding Spirit. All rights reserved.</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="Symbols count total">220k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="Reading time total">3:20</span>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="Total Visitors">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="Total Views">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
NexT.utils.loadComments(document.querySelector('#gitalk-container'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : '965ca656ae3d59a50b73',
      clientSecret: '94dbe9c760ce8b778c84481a7fe2f37f548d7375',
      repo        : 'blog-gitalk',
      owner       : 'codingspirit',
      admin       : ['codingspirit'],
      id          : '08d12546748b46f1a6614e743aadd814',
        language: '',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>

</body>
  
    <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas>
    <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script>
    <script type="text/javascript" src="/js/src/fireworks.js"></script>
  
</html>
